 
layui.define(['form','xmSelect','tableSelect','upload','admin','laydate'], function(exports){
	 var $ = layui.$
	    ,form = layui.form
	    ,setter = layui.setter
	    ,laydate = layui.laydate
	    ,tableSelect = layui.tableSelect
	    ,xmSelect = layui.xmSelect
		 ,admin = layui.admin
	 	,upload = layui.upload
		 ,count=0;
	    $("select[name='source']").attr("disabled","disabled");
		form.render('select');
	//日期
	laydate.render({
		elem: '#entry_time'
	});
	laydate.render({
		elem: '#birth'
	});
	laydate.render({
		elem: '#expire'
	});
	laydate.render({
		elem: '#entry_time'
	});
	laydate.render({
		elem: '#cj_riqi'
	});
	laydate.render({
		elem: '#gz_start'
	});
	laydate.render({
		elem: '#gz_over'
	});
	$('.layui-btn').on('click', function(){
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});
	var parentJson = {};

	var obj = {
		setParentJson: function setParentJson(json){
			parentJson = json;

		}
	}

	var active = {
		back: function(){
			backUrl();
		}
		,save:function(){
			form.on('submit(LAY-menu-add-submit)', function(data){
				let list = []
				let d = data.field
				if ((d["gz_start[0]"] == "") || (d["gz_over[0]"] == "") || (d["gz_bumen[0]"] == "") || (d["gz_gangwei[0]"] == "") ){

					delete d["gz_start[0]"]
					delete d["gz_over[0]"]
					delete d["gz_bumen[0]"]
					delete d["gz_gangwei[0]"]
				}else{
					for(let c = 0;c<=count;c++){
						let o = {}
						o['gz_start'] = d[`gz_start[${c}]`]
						delete d[`gz_start[${c}]`]
						o['gz_over'] = d[`gz_over[${c}]`]
						delete d[`gz_over[${c}]`]
						o['gz_bumen'] = d[`gz_bumen[${c}]`]
						delete d[`gz_bumen[${c}]`]
						o['gz_gangwei'] = d[`gz_gangwei[${c}]`]
						delete d[`gz_gangwei[${c}]`]
						list.push(o)
					}
					d.list = list
				}

				admin.req({
					url: setter.host+'/human/menu/insert'
					,type:'post'
					,dataType:'json'
					,contentType: "application/json; charset=utf-8"
					,data:JSON.stringify(d)
					,done: function(res){
						//请求成功后
						if(res.status == setter.response.statusCode.status_Success){
							// if(data.field.menuId == '-1'){
							// 	loadTable(colsArr,field);
							// }else{
							// 	renderTable.refresh(data.field.menuId);
							// }
							$('#LAY-menu-add-submit').attr("disabled","disabled");
							layer.msg(res.msg,{time:3000},function(){
								backUrl();
							});

							// form.render()
						}else {
							$('#LAY-menu-add-submit').attr("disabled","disabled");
							layer.msg(res.msg,{time:3000},function(){

							});

						}

					}
				});

			})
			$('[lay-filter="LAY-menu-add-submit"]').trigger('click');
		}
		,reset:function(){
			$('[lay-filter="layuiadmin-form-admin"]')[0].reset();
			form.render();
		}
	}
	function backUrl(){
		var bakUrl = parentJson.bakUrl;
		window.location.href = bakUrl;
	}

	function reld(){

		$(".riqi").each(function (){

			laydate.render({
				elem: this
			});
		})
	}
	var template=` <div class="layui-form-item">

          <label class="layui-form-label">开始日期</label>
          <div class="layui-input-inline">
              
              <input type="text" name="gz_start[]" id="gz_start" lay-verify="date" placeholder="例如2009-01-01" autocomplete="off" class="layui-input riqi">
          </div>
          <label class="layui-form-label">结束日期</label>
          <div class="layui-input-inline">
              <input type="text" name="gz_over[]" id="gz_over" lay-verify="date" placeholder="例如2009-01-01" autocomplete="off" class="layui-input riqi">
          </div>
          <label class="layui-form-label">部门</label>
          <div class="layui-input-inline">
              <input type="text" name="gz_bumen[]" id="gz_bumen" placeholder="所在部门" autocomplete="off" class="layui-input">
          </div>
          <label class="layui-form-label">岗位</label>
          <div class="layui-input-inline">
              <input type="text" name="gz_gangwei[]" id="gz_gangwei" placeholder="所在岗位" autocomplete="off" class="layui-input">
          </div>


      </div>`
	// form.on('button(addfield)',(data)=>{
	// 	console.log(123)
	// 	$("#gzjl").append(template)
	// })


	$("#addfield").click(()=>{
		$("#gzjl").append(template)
		reld()
		count++
		return false
	})



		var yicunzhao = upload.render({
			elem: "#yicunzhao"  // 指向容器选择器，与id进行绑定
			,url: setter.host+'/upload/imagesOss' //改成您自己的上传接口
			,accept:'images'
			,size:50000
			,before: function(obj){
				//预读本地文件示例，不支持ie8
				obj.preview(function(index, file, result){

					$('#yicunzhaodemo').attr('src', result);
					$('#yicunzhaodemo').show()//图片链接（base64）
				});
			}
			,done: function(res){
				//如果上传失败
				if(res.code != 0){
					layer.msg(res.msg);
				}
				//上传成功
				layer.msg(res.msg);
				//将图片的名字放在表单中，添加的时候得放在数据库里面
				$(function(){
					$("#yicunzhaopic").val(res.src);
					//alert('赋值成功');
				})
			}
			,error: function(){
				//演示失败状态，并实现重传
				var demoText = $('#yicunzhaoText');
				demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
				demoText.find('.demo-reload').on('click', function(){
					uploadInst.upload();
				});
			}
		});
		var gerenjianli = upload.render({
			elem:"#gerenjianli"
			,url: setter.host+'/upload/imagesOss' //改成您自己的上传接口
			,accept:'images'
			,size:50000
			,before: function(obj){
				//预读本地文件示例，不支持ie8
				obj.preview(function(index, file, result){
					$('#gerenjianlidemo').attr('src', result); //图片链接（base64）
					$('#gerenjianlidemo').show()
				});
			}
			,done: function(res){
				//如果上传失败
				if(res.code != 0){
					layer.msg(res.msg);
				}
				//上传成功
				layer.msg(res.msg);
				//将图片的名字放在表单中，添加的时候得放在数据库里面
				$(function(){
					$("#gerenjianlipic").val(res.src);
					//alert('赋值成功');
				})
			}
			,error: function(){
				//演示失败状态，并实现重传
				var demoText = $('#gerenjianliText');
				demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
				demoText.find('.demo-reload').on('click', function(){
					uploadInst.upload();
				});
			}
		})
		var gongzuozhaopian = upload.render({
			elem: "#gongzuozhaopian"  // 指向容器选择器，与id进行绑定
			,url: setter.host+'/upload/imagesOss' //改成您自己的上传接口
			,accept:'images'
			,size:50000
			,before: function(obj){
				//预读本地文件示例，不支持ie8
				obj.preview(function(index, file, result){
					$('#gongzuozhaopiandemo').attr('src', result); //图片链接（base64）
					$('#gongzuozhaopiandemo').show()
				});
			}
			,done: function(res){
				//如果上传失败
				if(res.code != 0){
					layer.msg(res.msg);
				}
				//上传成功
				layer.msg(res.msg);
				//将图片的名字放在表单中，添加的时候得放在数据库里面
				$(function(){
					$("#gongzuozhaopianpic").val(res.src);
					//alert('赋值成功');
				})
			}
			,error: function(){
				//演示失败状态，并实现重传
				var demoText = $('#gongzuozhaopiannameText');
				demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
				demoText.find('.demo-reload').on('click', function(){
					uploadInst.upload();
				});
			}
		});

// 	    var menuSelect = xmSelect.render({
// 			el: '#menuSelect',
// 			autoRow: true,
// 			name:'menuId',
// 			filterable:true,
// 			radio: true,
// 			clickClose: true,
// 			tree: {
// 				show: true,
// 				showFolderIcon: true,
// 				showLine: true,
// 				strict: false,
// 				indent: 20,
// 				expandedKeys: [ -3 ],
// 			},
// 			height: 'auto',
// 			on: function(data){
// 				if(data.isAdd){
// //					$('#menuSelect').find("input[name=menuId]").val(ids);
// 					$('input[name=pId]').val(data.change[0].pId);
// 				}
// 			}
// 		});
	  // $.ajax({
		//   url: setter.host+'/adminmanager/menu/queryTreeList'
	  //     ,type:'get'
	  //     ,dataType:'json'
	  //     ,success: function(res){
	  //       //请求成功后
	  //   	  if(res.status == setter.response.statusCode.status_Success){
	  //   		  menuSelect.update({
		//       		  data: res.data,
		//       		  autoRow: true,
		//       	  })
	  //   	  }else{
	  //   		  layer.msg(res.msg);
	  //   	  }
	  //     }
	  // });
	  //   form.on('select(typeSelect)',function (data){
	  //   	if(data.value=='button'){
	  //   		$('#url').val('add');
	  //   		$('#menuName1').find("input").val('新增');
		//     	$('#menuName1').css('display','none');
		//     	$('#menuName2').css('display','block');
		//     	$("select[name='source']").attr("disabled","disabled");
		//     	$("select[name='source']").val('self');
		//     	$('#selectSource').css('display','none');
		//     	form.render('select');
	  //   	}else if(data.value=='menu'){
	  //   		$('#url').val('');
	  //   		$('#menuName1').find("input").val('');
		//     	$('#menuName1').css('display','block');
		//     	$('#menuName2').css('display','none');
		//     	$("select[name='source']").removeAttr("disabled");
		//     	form.render('select');
	  //   	}else {
	  //   		$('#url').val('');
	  //   		$('#menuName1').find("input").val('');
		//     	$('#menuName1').css('display','block');
		//     	$('#menuName2').css('display','none');
		//     	$("select[name='source']").attr("disabled","disabled");
		//     	$("select[name='source']").val('self');
		//     	$('#selectSource').css('display','none');
		//     	form.render('select');
	  //   	}
	  //   });
	  //   form.on('select(sourceSelect)',function (data){
	  //   	if(data.value=='self'){
		//     	$('#selectSource').css('display','none');
	  //   	}else {
		//     	$('#selectSource').css('display','block');
	  //   	}
	  //   });
	  //   form.on('select(buttonSelect)',function (data){
      //       $("select[name='btnName']").next().find("dl").css({ "display": "none" });
      //       $("input[name='btnName']").val(data.elem[data.elem.selectedIndex].text);
      //
      //       $('#url').val(data.value);
      //       $('input[name="name"]').val(data.elem[data.elem.selectedIndex].text);
      //       form.render();
	  //   });
		// $("#icon").click(function(){
		// 	layer.open({
		// 		type: 2,
		// 		title:"图标管理 -- 当前共引入168个内置图标",
		// 		area:['95%', '95%'],
		// 		scrollbar:false,
		// 		content:setter.host+'/adminmanager/menu/toIcons',
		// 	});
		// 	return false;
		// });
	  //   $("#about1").mouseover(function() {
	  //   	layer.tips('设置该模块下的可见字段', this);
	  //   });


	    var colsArr = [
		                  { type: 'radio' },
		                  { field: 'moduleId', sort:true,title: '模块ID' },
		                  { field: 'moduleName', title: '模块名称' }
		              ];
		  var tableHead = '';
		  layui.each(colsArr,function(inx,val){
				tableHead += val.hasOwnProperty('field')?val.field+',':',';
		   	})
		   	//tableHead是获取表字段
	   tableHead = tableHead.substring(tableHead.indexOf(',')+1,tableHead.length-1);
		  tableSelect.render({
	       elem: '#modelSelect',
	       checkedKey: 'id',
	       height:'360',
	       width:'400',
	       searchType: 'more',
	       searchList: [
	           {searchKey: 'jobNum', searchPlaceholder: '搜索模块id'}
	       ],
	       table: {
	           url: layui.setter.host+'/adminmanager/menu/loadPlatformModel'
	           ,method:'post'
	           ,where:{'headField':tableHead}
	           ,contentType:'application/json; charset=utf-8'
	        	  ,page: true
		   		  ,groups:2
		   		  ,limit: 10
		   		  ,limits:[10,20,30]
	           ,text: {
		    	    none: '暂无相关数据' 
		    	  }
	           ,cols: [colsArr]
	       },
	       done: function (elem, data) {
	           var resultKey = []
	           var resultValue = []
	           var resultUrl = []
	           var resultField = []
	           layui.each(data.data, function (index, item) {
	        	   resultKey.push(item.moduleName);
	        	   resultValue.push(item.moduleId);
	        	   resultUrl.push(item.moduleUrl);
	        	   resultField.push(item.field);
	           })
	           elem.val(resultKey.join(","));
	           $("input[name='modelValue']").val(resultValue.join(","));
	           $("input[name='url']").val(resultUrl.join(","));
	           $("input[name='name']").val(resultKey.join(","));
	           $("input[name='field']").val(resultField.join(","));
	       }
	   });

  //对外暴露的接口
    exports('insert', obj);
});